# @Time : 2021/8/10
# @Author : 郝江波
# @Version：V 0.1
# @File : ImagePreHander.py
# @desc :
import os
import uuid
import cv2
import numpy as np


class ImagePreHander:
    tmpSavePath = "/tmp/"
    ratio = 0.5
    idDebuger = False

    def __init__(self, isDebuger):
        self.idDebuger = isDebuger

    # 预处理图片
    def predByFile(self, tmpFile):
        tmpPath = self.tmpSavePath + str(uuid.uuid1()) + ".jpg"
        tmpFile.save(tmpPath)
        img = cv2.imdecode(np.fromfile(tmpPath, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)
        img = cv2.GaussianBlur(img, (3, 3), 0)
        # img = cv2.resize(img, None, fy=self.ratio, fx=self.ratio, interpolation=cv2.INTER_NEAREST)
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
        close = cv2.erode(img, kernel, iterations=5)
        close = cv2.dilate(close, kernel, iterations=5)
        x = cv2.Sobel(close, cv2.CV_64F, dx=1, dy=0)
        y = cv2.Sobel(close, cv2.CV_64F, dx=0, dy=1)
        x = cv2.convertScaleAbs(x)
        y = cv2.convertScaleAbs(y)
        dst = cv2.addWeighted(x, 0.5, y, 0.5, 0)
        t, binaryImg = cv2.threshold(dst, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        contours, hierarchy = cv2.findContours(binaryImg, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE)
        tmpList = []
        area = 0
        maxRect = None
        resultImg = None
        for index in range(len(contours)):
            x, y, w, h = cv2.boundingRect(contours[index])
            tmparea = w * h
            if tmparea > area:
                area = tmparea
                # rectMat = img[y:y + h, x:x + w]
                if self.idDebuger:
                    print("w = {}  h = {} area = {}".format(w, h, area))

                brcnt = np.array([[x, y], [x + w, y], [x + w, y + h], [x, y + h]])
                maxRect = [x, y, w, h]
                resultImg = img[y:y + h, x:x + w]
                if self.idDebuger:
                    tmpList.append(brcnt)

        if self.idDebuger:
            dst = cv2.drawContours(img, [brcnt], -1, color=(0, 0, 255), thickness=1)
            cv2.imshow("result", cv2.resize(dst, None, fy=self.ratio, fx=self.ratio, interpolation=cv2.INTER_NEAREST))
            cv2.waitKey(0)
            cv2.destroyWindow("result")
        os.remove(tmpPath)
        return maxRect, resultImg
